package com.team2.cyber_eye;

import java.io.InputStream;

import com.team2.cyber_eye.ActivityHelpers.Util;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class CropActivity extends CyberActivity {

	CropView cropper;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState, R.layout.activity_crop, "Crop");
		
		Button saveButton = (Button)this.findViewById(R.id.SaveButton);
		saveButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SaveClick(); } });
		
		Button rotateButton = (Button)this.findViewById(R.id.RotateButton);
		rotateButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { cropper.Rotate(); } });
		cropper = (CropView)this.findViewById(R.id.cropView);
		
		try
		{
			Uri uri = this.getIntent().getData();
			InputStream is = this.getContentResolver().openInputStream(uri);
			Bitmap bmp = BitmapFactory.decodeStream(is);
			bmp = Util.LimitBitmap(bmp, 1024);//reduce memory errors
			cropper.SetImage(bmp);
		}
		catch (Exception ex)
		{
			Util.DisplayError(this, "Error loading image to crop", ex);
		}
	}
	
	protected void SaveClick()
	{
		try
		{
			Bitmap bmp = cropper.GetClipRegion();
			bmp = Util.LimitBitmap(bmp, 500);
			
			Intent intent = new Intent(); 
			intent.putExtra("data", bmp);
			
			setResult(Activity.RESULT_OK, intent);
			finish();
		}
		catch(Exception ex)
		{
			Util.DisplayError(this, "Error when cropping image", ex);
			setResult(Activity.RESULT_CANCELED);
			finish();
		}
		catch(OutOfMemoryError ex)
		{
			Util.DisplayIssue(this, "Out of memory when cropping image");
			setResult(Activity.RESULT_CANCELED);
			finish();
		}
	}
}
